package com.zxy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.swing.border.Border;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author: Zxy
 * @Date: 2021-06-09
 **/
@RestController
public class UserController {

    // 服务注册与发现的客户端对象
    @Autowired
    private DiscoveryClient discoveryClient;

    // 负载均衡的客户端对象，和上面的差不多，只不过上面的不能做负载均衡
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    @Qualifier(value = "restTemplate")
    private RestTemplate restTemplate;

    @GetMapping("/user")
    public String invokeDemo(){
        // 1.调用订单服务地址 http://localhost:9999/order 请求方式为get 返回String类型
        /*RestTemplate restTemplate = new RestTemplate();
        String orderResult = restTemplate.getForObject("http://localhost:9999/order", String.class);*/

        // 2.使用ribbon组件+RestTemplate实现负载均衡调用 1.DiscoverClient 2.LoadBalanceClient
        /*List<ServiceInstance> serviceInstances = discoveryClient.getInstances("ORDERS");
        String orderResult = new RestTemplate().getForObject(serviceInstances.get(0).getUri() + "/order", String.class);*/

        // 3.使用LoadBalance进行服务调用
        /*ServiceInstance instance = loadBalancerClient.choose("ORDERS");
        String orderResult = new RestTemplate().getForObject(instance.getUri() + "/order", String.class);*/
        // 使用自动注入的restTemplate
        /*ServiceInstance instance = loadBalancerClient.choose("ORDERS");
        String orderResult = restTemplate.getForObject(instance.getUri() + "/order", String.class);*/

        // 4.使用@LoadBalance注解，加在restTemplate上面 作用：可以让对象具有ribbon的负载均衡特性
        String orderResult = restTemplate.getForObject("http://ORDERS/order", String.class);
        return "ok"+orderResult;
    }
}
